package com.xbongbong.paas.help.subform;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.help.subform.abstracts.AbstractUserTeamTransferSubForm;
import com.xbongbong.saas.domain.entity.ClueUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.subform.ClueTeamEnum;
import org.springframework.stereotype.Component;

/**
 * @author long
 * @version v1.0
 * @date 2020/12/15 9:44
 * @since v1.0
 */
@Component
public class ClueTeamTransferSubForm extends AbstractUserTeamTransferSubForm {

    @Override
    public PaasFormDataEntity transferTeamToFormData(UserTeamEntity userTeamEntity) {
        ClueUserEntity clueUserEntity = (ClueUserEntity) userTeamEntity;
        PaasFormDataEntity paasFormDataEntity = createPaasFormDataEntityForUserTeam(userTeamEntity);

        JSONObject teamJson = JSONObject.parseObject(JSON.toJSONString(clueUserEntity));

        JSONObject data = new JSONObject();

        ClueTeamEnum[] clueTeamEnums = ClueTeamEnum.values();
        for (ClueTeamEnum clueTeamEnum : clueTeamEnums) {
            String dbAttr = clueTeamEnum.getDbAttr();
            String dataAttr = clueTeamEnum.getDataAttr();
            Integer fieldType = clueTeamEnum.getFieldType();
            formatDataForEs(teamJson, data, dbAttr, dataAttr, fieldType);
        }
        paasFormDataEntity.setData(data);

        return paasFormDataEntity;
    }


    @Override
    public UserTeamEntity transferFormDataToTeam(PaasFormDataEntity paasFormDataEntity) {

        JSONObject data = paasFormDataEntity.getData();

        JSONObject dbData = new JSONObject();
        ClueTeamEnum[] clueTeamEnums = ClueTeamEnum.values();
        for (ClueTeamEnum clueTeamEnum : clueTeamEnums) {
            String dbAttr = clueTeamEnum.getDbAttr();
            String dataAttr = clueTeamEnum.getDataAttr();
            Integer fieldType = clueTeamEnum.getFieldType();
            formatDataForDb(data, dbData, dbAttr, dataAttr, fieldType);

        }
        ClueUserEntity clueUserEntity = JSON.parseObject(dbData.toJSONString(), ClueUserEntity.class);
        clueUserEntity.setAddTime(paasFormDataEntity.getAddTime());
        clueUserEntity.setUpdateTime(paasFormDataEntity.getUpdateTime());
        clueUserEntity.setCorpid(paasFormDataEntity.getCorpid());
        clueUserEntity.setDel(paasFormDataEntity.getDel());
        clueUserEntity.setId(paasFormDataEntity.getId());

        return clueUserEntity;
    }
}
